{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let printing work the same in Python 2 and 3\n",
    "from __future__ import print_function\n",
    "# Turning on notebook plots -- just for use in jupyter notebooks.\n",
    "import matplotlib\n",
    "matplotlib.use('nbagg')\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How to speak \"MPL\"\n",
    "In the previous parts, you learned how Matplotlib organizes plot-making by figures and axes. We broke down the components of a basic figure and learned how to create them. You also learned how to add one or more axes to a figure, and how to tie them together. You even learned how to change some of the basic appearances of the axes. Finally, we went over some of the many plotting methods that Matplotlib has to draw on those axes. With all that knowledge, you should be off making great and wonderful figures.\n",
    "\n",
    "Why are you still here?\n",
    "\n",
    "\"We don't know how to control our plots and figures!\" says some random voice in the back of the room.\n",
    "\n",
    "Of course! While the previous sections may have taught you some of the structure and syntax of Matplotlib, it did not describe much of the substance and vocabulary of the library. This section will go over many of the properties that are used throughout the library. Note that while many of the examples in this section may show one way of setting a particular property, that property may be applicible elsewhere in completely different context. This is the \"language\" of Matplotlib.\n",
    "\n",
    "# Colors\n",
    "This is, perhaps, the most important piece of vocabulary in Matplotlib. Given that Matplotlib is a plotting library, colors are associated with everything that is plotted in your figures. Matplotlib supports a [very robust language](http://matplotlib.org/api/colors_api.html#module-matplotlib.colors) for specifying colors that should be familiar to a wide variety of users.\n",
    "\n",
    "### Colornames\n",
    "First, colors can be given as strings. For very basic colors, you can even get away with just a single letter:\n",
    "\n",
    "- b: blue\n",
    "- g: green\n",
    "- r: red\n",
    "- c: cyan\n",
    "- m: magenta\n",
    "- y: yellow\n",
    "- k: black\n",
    "- w: white\n",
    "\n",
    "Other colornames that are allowed are the HTML/CSS colornames such as \"burlywood\" and \"chartreuse\". See the [full list](https://www.w3schools.com/Colors/colors_names.asp) of the 140 color names. \n",
    "\n",
    "Matplotlib supports the [xkcd color names](https://xkcd.com/color/rgb/) prefxed by `'xkcd:'`.\n",
    "\n",
    "Matplotlib also understands  `{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}` which are the Tableau Colors from the ‘T10’ categorical palette (and the default color cycle);\n",
    "\n",
    "### Hex values\n",
    "Colors can also be specified by supplying a HTML/CSS hex string, such as `'#0000FF'` for blue. Support for an optional alpha channel was added for v2.0.\n",
    "\n",
    "### 256 Shades of Gray\n",
    "A gray level can be given instead of a color by passing a string representation of a number between 0 and 1, inclusive. `'0.0'` is black, while `'1.0'` is white. `'0.75'` would be a light shade of gray.\n",
    "\n",
    "### Cycle references\n",
    "With the advent of fancier color cycles coming from the many available styles, users needed a way to reference those colors in the style without explicitly knowing what they are. So, in v2.0, the ability to reference the first 10 iterations of the color cycle was added. Whereever one could specify a color, you can supply a 2 character string of 'C#'. So, 'C0' would be the first color, 'C1' would be the second, and so on and so forth up to 'C9'.\n",
    "\n",
    "### RGB[A] tuples\n",
    "You may come upon instances where the previous ways of specifying colors do not work. When all else fails, the universal language of colors for matplotlib is the RGB[A] tuple. This is the \"Red\", \"Green\", \"Blue\", and sometimes \"Alpha\" tuple of floats in the range of [0, 1]. One means full saturation of that channel, so a red RGBA tuple would be `(1.0, 0.0, 0.0, 1.0)`, whereas a partly transparent green RGBA tuple would be `(0.0, 1.0, 0.0, 0.75)`.  The documentation will usually specify whether it accepts RGB or RGBA tuples. Sometimes, a list of tuples would be required for multiple colors, and you can even supply a Nx3 or Nx4 numpy array in such cases.\n",
    "\n",
    "In functions such as `plot()` and `scatter()`, while it may appear that they can take a color specification, what they really need is a \"format specification\", which includes color as part of the format. Unfortunately, such specifications are string only and so RGB[A] tuples are not supported for such arguments (but you can still pass an RGB[A] tuple for a \"color\" argument).\n",
    "\n",
    "Oftentimes there is a separate argument for \"alpha\" where-ever you can specify a color. The value for \"alpha\" will usually take precedence over the alpha value in the RGBA tuple. There is no easy way around this inconsistency.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 3.1\n",
    "Try out some different string representations of colors (you can't do RGB[A] tuples here)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load exercises/3.1-colors.py\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = np.arange(0.0, 5.0, 0.2)\n",
    "plt.plot(t, t, t, t**2, t, t**3)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Markers\n",
    "[Markers](http://matplotlib.org/api/markers_api.html) are commonly used in [`plot()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot) and [`scatter()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter) plots, but also show up elsewhere. There is a wide set of markers available, and custom markers can even be specified.\n",
    "\n",
    "marker     |  description  | marker    |  description    | marker   |  description  | marker    |  description  \n",
    ":----------|:--------------|:----------|:----------------|:---------|:--------------|:----------|:--------------\n",
    "\".\"        |  point        | \"+\"       |  plus           | \",\"      |  pixel        | \"x\"       |  cross\n",
    "\"o\"        |  circle       | \"D\"       |  diamond        | \"d\"      |  thin_diamond |           |\n",
    "\"8\"        |  octagon      | \"s\"       |  square         | \"p\"      |  pentagon     | \"\\*\"      |  star\n",
    "\"&#124;\"   |  vertical line| \"\\_\"      | horizontal line |  \"h\"     |  hexagon1     | \"H\"       |  hexagon2\n",
    "0          |  tickleft     | 4         |  caretleft      | \"<\"      | triangle_left | \"3\"       |  tri_left\n",
    "1          |  tickright    | 5         |  caretright     | \">\"      | triangle_right| \"4\"       |  tri_right\n",
    "2          |  tickup       | 6         |  caretup        | \"^\"      | triangle_up   | \"2\"       |  tri_up\n",
    "3          |  tickdown     | 7         |  caretdown      | \"v\"      | triangle_down | \"1\"       |  tri_down\n",
    "\"None\"     |  nothing      | `None`    |  default        | \" \"      |  nothing      | \"\"        |  nothing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xs, ys = np.mgrid[:4, 9:0:-1]\n",
    "markers = [\".\", \"+\", \",\", \"x\", \"o\", \"D\", \"d\", \"\", \"8\", \"s\", \"p\", \"*\", \"|\", \"_\", \"h\", \"H\", 0, 4, \"<\", \"3\",\n",
    "           1, 5, \">\", \"4\", 2, 6, \"^\", \"2\", 3, 7, \"v\", \"1\", \"None\", None, \" \", \"\"]\n",
    "descripts = [\"point\", \"plus\", \"pixel\", \"cross\", \"circle\", \"diamond\", \"thin diamond\", \"\",\n",
    "             \"octagon\", \"square\", \"pentagon\", \"star\", \"vertical bar\", \"horizontal bar\", \"hexagon 1\", \"hexagon 2\",\n",
    "             \"tick left\", \"caret left\", \"triangle left\", \"tri left\", \"tick right\", \"caret right\", \"triangle right\", \"tri right\",\n",
    "             \"tick up\", \"caret up\", \"triangle up\", \"tri up\", \"tick down\", \"caret down\", \"triangle down\", \"tri down\",\n",
    "             \"Nothing\", \"default\", \"Nothing\", \"Nothing\"]\n",
    "fig, ax = plt.subplots(1, 1, figsize=(7.5, 4))\n",
    "for x, y, m, d in zip(xs.T.flat, ys.T.flat, markers, descripts):\n",
    "    ax.scatter(x, y, marker=m, s=100)\n",
    "    ax.text(x + 0.1, y - 0.1, d, size=14)\n",
    "ax.set_axis_off()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 3.2\n",
    "Try out some different markers and colors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load exercises/3.2-markers.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = np.arange(0.0, 5.0, 0.2)\n",
    "plt.plot(t, t, , t, t**2, , t, t**3, )\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Linestyles\n",
    "Line styles are about as commonly used as colors. There are a few predefined linestyles available to use. Note that there are some advanced techniques to specify some custom line styles. [Here](http://matplotlib.org/1.3.0/examples/lines_bars_and_markers/line_demo_dash_control.html) is an example of a custom dash pattern.\n",
    "\n",
    "linestyle          | description\n",
    "-------------------|------------------------------\n",
    "'-'                | solid\n",
    "'--'               | dashed\n",
    "'-.'               | dashdot\n",
    "':'                | dotted\n",
    "'None'             | draw nothing\n",
    "' '                | draw nothing\n",
    "''                 | draw nothing\n",
    "\n",
    "Also, don't mix up \".-\" (line with dot markers) and \"-.\" (dash-dot line) when using the ``plot`` function!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = np.arange(0.0, 5.0, 0.2)\n",
    "plt.plot(t, t, '-', t, t**2, '--', t, t**3, '-.', t, -t, ':')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is a bit confusing, but the line styles mentioned above are only valid for lines. Whenever you are dealing with the linestyles of the edges of \"Patch\" objects, you will need to use words instead of the symbols. So \"solid\" instead of \"-\", and \"dashdot\" instead of \"-.\". This issue will be fixed for the v2.1 release and allow these specifications to be used interchangably."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(1, 1)\n",
    "ax.bar([1, 2, 3, 4], [10, 20, 15, 13], ls='dashed', ec='r', lw=5)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot attributes\n",
    "With just about any plot you can make, there are many attributes that can be modified to make the lines and markers suit your needs. Note that for many plotting functions, Matplotlib will cycle the colors for each dataset you plot. However, you are free to explicitly state which colors you want used for which plots. For [`plt.plot()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot), you can mix the specification for the colors, linestyles, and markers in a single string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = np.arange(0., 5., 0.2)\n",
    "# red dashes, blue squares and green triangles\n",
    "plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Property               | Value Type                                      \n",
    "|------------------------|-------------------------------------------------\n",
    "|alpha                   | float                                           \n",
    "|color or c              | any matplotlib color                            \n",
    "|dash_capstyle           | ['butt', 'round' 'projecting']               \n",
    "|dash_joinstyle          | ['miter' 'round' 'bevel']\n",
    "|dashes                  | sequence of on/off ink in points                \n",
    "|drawstyle               | [ ‘default’ ‘steps’ ‘steps-pre’\n",
    "|                        |   ‘steps-mid’ ‘steps-post’ ]\n",
    "|linestyle or ls         | [ '-' '--' '-.' ':' 'None' ' ' ''] \n",
    "|                        | and any drawstyle in combination with a         \n",
    "|                        | linestyle, e.g. 'steps--'.                      \n",
    "|linewidth or lw         | float value in points                           \n",
    "|marker                  | [ 0 1 2 3 4 5 6 7 'o' 'd' 'D' 'h' 'H'\n",
    "|                        |  '' 'None' ' ' `None` '8' 'p' ','\n",
    "|                        |  '+' 'x' '.' 's' '\\*' '\\_' '&#124;'\n",
    "|                        |  '1' '2' '3' '4' 'v' '<' '>' '^' ]\n",
    "|markeredgecolor or mec  | any matplotlib color\n",
    "|markeredgewidth or mew  | float value in points\n",
    "|markerfacecolor or mfc  | any matplotlib color\n",
    "|markersize or ms        | float\n",
    "|solid_capstyle          | ['butt' 'round' 'projecting']\n",
    "|solid_joinstyle         | ['miter' 'round' 'bevel']\n",
    "|visible                 | [`True` `False`]\n",
    "|zorder                  | any number\n",
    "\n",
    "## Exercise 3.3\n",
    "Make a plot that has a dotted red line, with large yellow diamond markers that have a green edge"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load exercises/3.3-properties.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = np.arange(0.0, 5.0, 0.1)\n",
    "a = np.exp(-t) * np.cos(2*np.pi*t)\n",
    "plt.plot(t, a, )\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Colormaps\n",
    "Another very important property of many figures is the colormap. The job of a colormap is to relate a scalar value to a color. In addition to the regular portion of the colormap, an \"over\", \"under\" and \"bad\" color can be optionally defined as well. NaNs will trigger the \"bad\" part of the colormap.\n",
    "\n",
    "As we all know, we create figures in order to convey information visually to our readers. There is much care and consideration that have gone into the design of these colormaps. Your choice in which colormap to use depends on what you are displaying. In mpl, the \"jet\" colormap has historically been used by default, but it will often not be the colormap you would want to use. Much discussion has taken place on the mailing lists with regards to what colormap should be default. The v2.0 release of Matplotlib adopted a new default colormap, 'viridis', along with some other stylistic changes to the defaults.\n",
    "\n",
    "I want to acknowedge Nicolas Rougier and Tony Yu for putting significant effort in educating users in proper colormap selections. Furthermore, thanks goes to Nathaniel Smith and Stéfan van der Walt for developing the new perceptually uniform colormaps such as viridis. [Here is the talk](https://www.youtube.com/watch?v=xAoljeRJ3lU) they gave at SciPy 2015 that does an excelent job explaining colormaps.\n",
    "\n",
    "Here is the full gallery of all the pre-defined colormaps, organized by the types of data they are usually used for."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# %load http://matplotlib.org/mpl_examples/color/colormaps_reference.py\n",
    "\"\"\"\n",
    "==================\n",
    "Colormap reference\n",
    "==================\n",
    "\n",
    "Reference for colormaps included with Matplotlib.\n",
    "\n",
    "This reference example shows all colormaps included with Matplotlib. Note that\n",
    "any colormap listed here can be reversed by appending \"_r\" (e.g., \"pink_r\").\n",
    "These colormaps are divided into the following categories:\n",
    "\n",
    "Sequential:\n",
    "    These colormaps are approximately monochromatic colormaps varying smoothly\n",
    "    between two color tones---usually from low saturation (e.g. white) to high\n",
    "    saturation (e.g. a bright blue). Sequential colormaps are ideal for\n",
    "    representing most scientific data since they show a clear progression from\n",
    "    low-to-high values.\n",
    "\n",
    "Diverging:\n",
    "    These colormaps have a median value (usually light in color) and vary\n",
    "    smoothly to two different color tones at high and low values. Diverging\n",
    "    colormaps are ideal when your data has a median value that is significant\n",
    "    (e.g.  0, such that positive and negative values are represented by\n",
    "    different colors of the colormap).\n",
    "\n",
    "Qualitative:\n",
    "    These colormaps vary rapidly in color. Qualitative colormaps are useful for\n",
    "    choosing a set of discrete colors. For example::\n",
    "\n",
    "        color_list = plt.cm.Set3(np.linspace(0, 1, 12))\n",
    "\n",
    "    gives a list of RGB colors that are good for plotting a series of lines on\n",
    "    a dark background.\n",
    "\n",
    "Miscellaneous:\n",
    "    Colormaps that don't fit into the categories above.\n",
    "\n",
    "\"\"\"\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "# Have colormaps separated into categories:\n",
    "# http://matplotlib.org/examples/color/colormaps_reference.html\n",
    "cmaps = [('Perceptually Uniform Sequential', [\n",
    "            'viridis', 'plasma', 'inferno', 'magma']),\n",
    "         ('Sequential', [\n",
    "            'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',\n",
    "            'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',\n",
    "            'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),\n",
    "         ('Sequential (2)', [\n",
    "            'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',\n",
    "            'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',\n",
    "            'hot', 'afmhot', 'gist_heat', 'copper']),\n",
    "         ('Diverging', [\n",
    "            'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',\n",
    "            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']),\n",
    "         ('Qualitative', [\n",
    "            'Pastel1', 'Pastel2', 'Paired', 'Accent',\n",
    "            'Dark2', 'Set1', 'Set2', 'Set3',\n",
    "            'tab10', 'tab20', 'tab20b', 'tab20c']),\n",
    "         ('Miscellaneous', [\n",
    "            'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',\n",
    "            'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'hsv',\n",
    "            'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'])]\n",
    "\n",
    "\n",
    "nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps)\n",
    "gradient = np.linspace(0, 1, 256)\n",
    "gradient = np.vstack((gradient, gradient))\n",
    "\n",
    "\n",
    "def plot_color_gradients(cmap_category, cmap_list, nrows):\n",
    "    fig, axes = plt.subplots(nrows=nrows)\n",
    "    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)\n",
    "    axes[0].set_title(cmap_category + ' colormaps', fontsize=14)\n",
    "\n",
    "    for ax, name in zip(axes, cmap_list):\n",
    "        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))\n",
    "        pos = list(ax.get_position().bounds)\n",
    "        x_text = pos[0] - 0.01\n",
    "        y_text = pos[1] + pos[3]/2.\n",
    "        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)\n",
    "\n",
    "    # Turn off *all* ticks & spines, not just the ones with colormaps.\n",
    "    for ax in axes:\n",
    "        ax.set_axis_off()\n",
    "\n",
    "\n",
    "for cmap_category, cmap_list in cmaps:\n",
    "    plot_color_gradients(cmap_category, cmap_list, nrows)\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When colormaps are created in mpl, they get \"registered\" with a name. This allows one to specify a colormap to use by name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, (ax1, ax2) = plt.subplots(1, 2)\n",
    "z = np.random.random((10, 10))\n",
    "ax1.imshow(z, interpolation='none', cmap='gray')\n",
    "ax2.imshow(z, interpolation='none', cmap='coolwarm')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Mathtext\n",
    "Oftentimes, you just simply need that superscript or some other math text in your labels. Matplotlib provides a very easy way to do this for those familiar with LaTeX. Any text that is surrounded by dollar signs will be treated as \"[mathtext](http://matplotlib.org/users/mathtext.html#mathtext-tutorial)\". Do note that because backslashes are prevelent in LaTeX, it is often a good idea to prepend an `r` to your string literal so that Python will not treat the backslashes as escape characters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter([1, 2, 3, 4], [4, 3, 2, 1])\n",
    "plt.title(r'$\\sigma_i=15$', fontsize=20)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Hatches\n",
    "A Patch object can have a hatching defined for it.\n",
    "\n",
    "* /   - diagonal hatching\n",
    "* \\   - back diagonal\n",
    "* |   - vertical\n",
    "* \\-   - horizontal\n",
    "* \\+   - crossed\n",
    "* x   - crossed diagonal\n",
    "* o   - small circle\n",
    "* O   - large circle (upper-case 'o')\n",
    "* .   - dots\n",
    "* \\*   - stars\n",
    "     \n",
    "Letters can be combined, in which case all the specified\n",
    "hatchings are done.  Repeating a character increases the\n",
    "density of hatching of that pattern."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Property Cycles\n",
    "In case you haven't noticed, when you do multiple plot calls in the same axes -- and not specify any colors -- the color for each plot is different! The default style in Matplotlib will cycle through a list of colors if you don't specify any. This feature has been in Matplotlib for a long time and it is similar to Matlab behavior.\n",
    "\n",
    "In v1.5, this feature was extended so that one can cycle through other properties besides just color. Now, you can cycle linestyles, markers, hatch styles -- just about any property that can be specified is now possible to be cycled.\n",
    "\n",
    "This feature is still being refined, and there has been significant improvements in its usability since v1.5, but here is a basic example that will work for v2.0 or greater (for v1.5, you may need to have this cycler expression quoted)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib as mpl\n",
    "from matplotlib.rcsetup import cycler\n",
    "mpl.rc('axes', prop_cycle=cycler('color', 'rgc') +\n",
    "                          cycler('lw', [1, 4, 6]) +\n",
    "                          cycler('linestyle', ['-', '-.', ':']))\n",
    "t = np.arange(0.0, 5.0, 0.2)\n",
    "plt.plot(t, t)\n",
    "plt.plot(t, t**2)\n",
    "plt.plot(t, t**3)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Ugly tie contest!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mpl.rc('axes', prop_cycle=cycler('color', ['r', 'orange', 'c', 'y']) +\n",
    "                          cycler('hatch', ['x', 'xx-', '+O.', '*']))\n",
    "x = np.array([0.7, 0.3, 0.385, 0.6153, 0.7, np.nan, 0.6, 0.4, 0.2, 0.5, 0.8, 0.6])\n",
    "y = [0.65, 0.65, 0.1, 0.1, 0.65, np.nan, 0, 0, -5, -6, -5, 0]\n",
    "plt.fill(x+1, y)\n",
    "plt.fill(x+2, y)\n",
    "plt.fill(x+3, y)\n",
    "plt.fill(x+4, y)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Transforms\n",
    "The topic of transforms in Matplotlib, that is the ability to map the coordinates specified by your data to the coordinates of your figure, is very advanced and will not be covered in this tutorial. For those who are interested in learning about them, see the [transformation tutorial](http://matplotlib.org/users/transforms_tutorial.html). For those who are really daring, there are the developer guides to [transforms](http://matplotlib.org/devel/transformations.html) and [scales](http://matplotlib.org/devel/add_new_projection.html). While most users will never, ever need to understand Matplotlib transforms to the level described in those links, it is important to be aware of them, and their critical role in figure-making.\n",
    "\n",
    "In a figure, there are four coordinate systems: *display*, *figure*, *axes*, and *data*. Transforms are used to convert coordinates in one system into another system for various uses. This is how Matplotlib knows exactly where to place the ticks and ticklabels, even when you change the axis limits. The ticker says that the tick and label \"1.5\", for example, are to go at data x-coordinate 1.5. The transform says that location is at 0.4 in axes x-coordinate space. Meanwhile, the xlabel of \"Distance\" is placed at axes x-coordinate space of 0.5 (half-way). Meanwhile, a legend might be placed at a location relative to the figure coordinates.\n",
    "\n",
    "Furthermore, the transform system is what is used to allow various scales to work, such as log scales. The transform system is what is used to make the polar plots work seamlessly. Whether you realize it or not, you use the transforms system in Matplotlib all the time. Everything drawn in Matplotlib has a transform associated with it. Most of the time, you will never notice this, and will happily operate within the *data* coordinate system. But when you want to do some more advanced plots, with some eye-catching visual tricks, the transform system will be there for you."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Managing the unmanagable -- Introducing matplotlibrc\n",
    "Matplotlib's greatest strength is its ability to give you complete control over every single aspect of your plots and figures. Matplotlib's second greatest strength is its ability to take as much control over as much of your plots and figures as you want. You, as the user, would never consider to use Matplotlib if you had to specify all of these things for every single plot. Most of the time, the defaults are exactly what you want them to be.\n",
    "\n",
    "Matplotlib uses the matplotlibrc configuration file to define the plethora of defaults found in the library. You can control the defaults of almost every property in Matplotlib: figure size and dpi, line width, color and style, axes, axis and grid properties, text and font properties and so on. Just modify your rc file and re-run your scripts to produce your improved figures.\n",
    "\n",
    "To display where the currently active matplotlibrc file was loaded from, one can do the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib\n",
    "print(matplotlib.matplotlib_fname())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also change the rc settings during runtime within a python script or interactively from the python shell. All of the rc settings are stored in a dictionary-like variable called [`matplotlib.rcParams`](http://matplotlib.org/api/matplotlib_configuration_api.html#matplotlib.matplotlib.rcParams), which is global to the matplotlib package. `rcParams` can be modified directly. Newer versions of matplotlib can use [`rc()`](http://matplotlib.org/api/matplotlib_configuration_api.html#matplotlib.rc), for example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt\n",
    "mpl.rcdefaults()  # for when re-running this cell\n",
    "\n",
    "fig, (ax1, ax2) = plt.subplots(1, 2)\n",
    "ax1.plot([1, 2, 3, 4])\n",
    "\n",
    "mpl.rc('lines', linewidth=2, linestyle='-.')\n",
    "# Equivalent older, but still valid syntax\n",
    "#mpl.rcParams['lines.linewidth'] = 2\n",
    "#mpl.rcParams['lines.linestyle'] = '-.'\n",
    "ax2.plot([1, 2, 3, 4])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To learn more, please see this guide on [customizing matplotlib](http://matplotlib.org/users/customizing.html)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
